<template>
  <div class="main-header">
    <div class="logo">
      <img src="@/assets/img/logo.png">
      <div class="label">微信点餐后台管理</div>
    </div>
    <div class="info" v-if="status.showFlag">
      <div class="shop-area" style="border-right: 2px solid rgba(102, 102, 102, 1);margin-left: 10px">
        <el-badge :value="status.unReadNotice.length" v-if="status.unReadNotice.length > 0">
          <i class="iconfont my-icon-24gf-envelope2 mg-icon" style="font-size: 19px;color: #606266" @click="goNoticeList"></i>
        </el-badge>
        <i class="iconfont my-icon-24gf-envelope2 mg-icon" style="font-size: 19px;color: #606266" @click="goNoticeList" v-else></i>
        <div style="margin-right: 5px"></div>
      </div>
      <el-dropdown v-if="status.needDealNum > 0">
        <div class="shop-area" style="border-right: 2px solid rgba(102, 102, 102, 1);margin-left: 10px;">
          <el-badge :value="status.needDealNum" v-if="status.needDealNum > 0">
            <i class="iconfont my-icon-lingdang mg-icon" style="font-size: 19px;"></i>
          </el-badge>
          <i class="iconfont my-icon-lingdang mg-icon" style="font-size: 19px;" v-else></i>
          <div style="margin-right: 5px"></div>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="goUnAcceptOrderList">待接单({{ status.unAcceptedOrderList.length }})</el-dropdown-item>
            <el-dropdown-item @click="goUnCompletedOrderList">未完成({{ status.unCompletedOrderList.length }})</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div class="shop-area" style="border-right: 2px solid rgba(102, 102, 102, 1);margin-left: 10px" v-if="status.shopList.length === 1">
        <i class="iconfont my-icon-shangdian"></i>
        <div class="shop-name">{{ status.shopName }}</div>
        <i class="iconfont my-icon-xiangxia mg-icon"></i>
      </div>
      <el-dropdown v-if="status.shopList.length > 1">
        <div class="shop-area" style="border-right: 2px solid rgba(102, 102, 102, 1);margin-left: 10px">
          <i class="iconfont my-icon-shangdian"></i>
          <div class="shop-name">{{ status.shopName }}</div>
          <i class="iconfont my-icon-xiangxia mg-icon"></i>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="item in status.shopList.filter((item) => item.shopId !== status.shopId)" :key="item.shopId" @click="changeNowShop(item.shopId)" style="display: flex; align-items: center">
              {{ item.shopName }}
              <el-tag v-if="item.state === 1" type="warning" size="mini" style="margin-left: 10px">申请中</el-tag>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-dropdown>
        <div class="shop-area" style="margin-left: 10px">
          <i class="iconfont my-icon-geren"></i>
          <div class="shop-name">{{ status.userName }}</div>
          <i class="iconfont my-icon-xiangxia" style="margin-right: 10px"></i>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="signOut">
              退出
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import router from "@/router";
import {ElMessage} from "element-plus";
import VueCookies from "vue-cookies";
import {inject, nextTick, onMounted, reactive, defineEmits,} from "vue";
import {httpPostManage, jzjUrl} from "@/api/httpService";

const emit = defineEmits(['fatherFn']);

const reload = inject("reload"); //重新加载主页面

const status = reactive({
  socket: null,
  showFlag: false,
  userName: localStorage.getItem("userName"),
  shopId: localStorage.getItem("shopId") ? localStorage.getItem("shopId") : null,
  shopName: localStorage.getItem("shopName") ? localStorage.getItem("shopName") : null,
  shopList: [],
  unReadNotice: [],
  unAcceptedOrderList: [],
  unCompletedOrderList: [],
  needDealNum: 0
});

const signOut = () => {
  VueCookies.remove("tokenWeb");
  localStorage.removeItem("userName");
  localStorage.removeItem("shopName");
  localStorage.removeItem("shopId");
  ElMessage.success("退出成功");
  router.push({name: 'Login'});
}

const shopOwnerSearch = async () => {
  status.showFlag = false;
  let url = "/shopOwnerSearch";
  let res = await httpPostManage(url, {});
  status.shopList = res.data;
  if (res.data.length !== 0) {
    if (!status.shopId) {
      localStorage.setItem("shopName", res.data[0]["shopName"]);
      localStorage.setItem("shopId", res.data[0]["shopId"]);
      status.shopId = res.data[0]["shopId"];
      status.shopName = res.data[0]["shopName"];
    }
  }
  await changeNowShopToken(status.shopId);
  emit("checkIfPassed");
  await nextTick(() => {
    status.showFlag = true;
  })
};

const changeNowShopToken = async (shopId) => {
  let url = "/changeNowShopToken";
  let params = {
    keywords: shopId
  };
  let res = await httpPostManage(url, params);
  VueCookies.remove("tokenWeb");
  VueCookies.set("tokenWeb", res.data, 24 * 60 * 60);
};

const changeNowShop = (id) => {
  let shopItem = status.shopList.filter((item) => item.shopId === id)[0];
  localStorage.setItem("shopName", shopItem["shopName"]);
  localStorage.setItem("shopId", shopItem["shopId"]);
  reload();
  router.push("/shopOwner/excessive");
  router.push("/shopOwner/orderList");
};

/**
 * webSocket模块
 * */
const openSocket = () => {
  if (typeof WebSocket == "undefined") {
    console.log("您的浏览器不支持WebSocket");
  } else {
    console.log("您的浏览器支持WebSocket");
    //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
    let socketUrl = jzjUrl + "/pushOrder/" + status.shopId;
    socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
    console.log(socketUrl);
    if (status.socket != null) {
      status.socket.close();
      status.socket = null;
    }
    status.socket = new WebSocket(socketUrl);
    //打开事件
    status.socket.onopen = function() {
      console.log("websocket已打开");
      //socket.send("这是来自客户端的消息" + location.href + new Date());
    };
    //获得消息事件
    status.socket.onmessage = async function (res) {
      console.log(res.data)
      if (res.data !== "连接成功" && res.data !== "阅读完毕") {
        const synth = window.speechSynthesis; // 启用文本
        const msg = new SpeechSynthesisUtterance();
        msg.text = res.data; // 文字内容: 测试内容
        msg.lang = "zh-CN"; // 使用的语言:中文
        msg.volume = 1; // 声音音量：1
        msg.rate = 1; // 语速：1
        msg.pitch = 1; // 音高：1
        synth.speak(msg); // 播放
      }
      await getUnAcceptedOrder();
      await getUnreadNotice();
      //发现消息进入    开始处理前端触发逻辑
    };
    //关闭事件
    status.socket.onclose = function() {
      console.log("websocket已关闭");
    };
    //发生了错误事件
    status.socket.onerror = function() {
      console.log("websocket发生了错误");
    };
  }
};

const getUnAcceptedOrder = async () => {
  let url = "/getUnAcceptedOrder";
  let res = await httpPostManage(url, {});
  status.unAcceptedOrderList = res.data["unAcceptedOrder"];
  status.unCompletedOrderList = res.data["unCompletedOrder"];
  status.needDealNum = res.data["unAcceptedOrder"].length + res.data["unCompletedOrder"].length;
};

const getUnreadNotice = async () => {
  let url = "/getUnreadNotice";
  let res = await httpPostManage(url, {});
  status.unReadNotice = res.data;
};

const goUnAcceptOrderList = () => {
  router.push(
      {
        name: "OrderList",
        query: {
          state: "2"
        }
      }
  )
};

const goUnCompletedOrderList = () => {
  router.push(
      {
        name: "OrderList",
        query: {
          state: "3"
        }
      }
  )
};

const goNoticeList = () => {
  router.push("/shopOwner/noticeList");
}

onMounted(async () => {
  await shopOwnerSearch();
  await openSocket();
});
</script>

<style lang="scss" scoped>
.main-header {
  width: 100%;
  height: 100%;
  background-color: rgba(249, 249, 249, 1);
  border-bottom: 1px solid #d5d5d5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .logo {
    display: flex;
    align-items: center;
    img {
      height: 40px;
      width: 40px;
    }
    .label {
      height: 26px;
      color: rgba(16, 16, 16, 1);
      font-size: 18px;
    }
  }
  .info {
    margin-right: 20px;
    display: flex;
    align-items: center;
    .shop-area{
      display: flex;
      align-items: center;
      cursor: pointer;
      .shop-name {
        margin-left: 10px;
        margin-right: 5px;
        margin-top: -1px;
        font-size: 16px;
      }
      .mg-icon {
        margin-right: 10px;
      }
      :deep .el-badge {
        .el-badge__content {
          height: 12px;
          font-size: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          transform: translateY(-50%) translateX(60%);
        }
      }
    }
    :deep.el-popover {
      padding: 10px 0 !important;
    }
  }
}
</style>